//
//  templateAppDelegate.m
//  template
//
//  Created by SIO2 Interactive on 8/22/08.
//  Copyright SIO2 Interactive 2008. All rights reserved.
//

//File modified by Goffredo Marocchi (this is not the original SIO2 provided file,
//sio2 and its creator ROm are not responsible for the content of this file as it is now

#import "templateAppDelegate.h"
#import "EAGLView.h"
#import "cocos2d.h"
#import "HelloWorldScene.h"
#import "SysTools.h"
#import "Reachability.h"

#import "png.h"

@implementation templateAppDelegate

@synthesize window, glView, online;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	
	int shift_a = -4;
	
	[SysTools testRightShift];
	[SysTools testIsNumber];
	
	//if ([UIDevice currentDevice].multitaskingSupported) NSLog(@"iOS4...");
	
	[SysTools sendOrientationNotifications:@selector(didRotateMethod:) to:self];
	
	online = NO;

	// Init the window
	//window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	
	glView.animationInterval = 1.0 / 60.0;
	[glView startAnimation];
	
	// Flip the simulator to the right
	[[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeRight
													  animated: NO];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:( 1.0f / 30.0f )];
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];		
	
	// Try to use CADisplayLink director
	// if it fails (SDK < 3.1) use the default director
	if( ! [CCDirector setDirectorType:CCDirectorTypeDisplayLink] )
		[CCDirector setDirectorType:CCDirectorTypeDefault];
	
	// Use RGBA_8888 buffers
	// Default is: RGB_565 buffers
	[[CCDirector sharedDirector] setPixelFormat:kPixelFormatRGBA8888];
	
	// Create a depth buffer of 16 bits
	// Enable it if you are going to use 3D transitions or 3d objects
	//	[[CCDirector sharedDirector] setDepthBufferFormat:kDepthBuffer16];
	
	// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
	// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
	// You can change anytime.
	[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
	
	
	// before creating any layer, set the landscape mode
	[[CCDirector sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];
	[[CCDirector sharedDirector] setAnimationInterval:1.0/60];
		
	//[window makeKeyAndVisible];		
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	NSLog(@"Application Did Become Active");
	[glView startAnimation];
}

- (void)applicationWillResignActive:(UIApplication *)application {
	NSLog(@"Application Will Resign Active");
	[glView stopAnimation];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     DidEnterBackground --> WillEnterForeground --> DidBecomeActive
	 */
	NSLog(@"Application has entered foreground");
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
	NSLog(@"Application has entered background");
}

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate and multi-tasking is not supported.
     See also applicationDidEnterBackground:.
     */
	NSLog(@"Application Will Terminate... iOS < 4.0 or backgrounding disabled");
	[glView stopAnimation];
}

- (void)didRotateMethod:(NSNotification*) sender {
	
	UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
	
	switch (deviceOrientation) {
		case UIDeviceOrientationUnknown:
			break;
		case UIDeviceOrientationLandscapeLeft:
			NSLog(@"Landscape left");
			break;
		case UIDeviceOrientationLandscapeRight:
			NSLog(@"Landscape right");
			break;
		case UIDeviceOrientationPortrait:
			NSLog(@"Portrait up");
			break;
		case UIDeviceOrientationPortraitUpsideDown:
			NSLog(@"Portrait down");
			break;
		case UIDeviceOrientationFaceUp:
			NSLog(@"Face up");
			break;
		case UIDeviceOrientationFaceDown:
			NSLog(@"Face Down");
			break;
		default:
			NSLog(@"deviceOrientation = %i", deviceOrientation);
			NSAssert(FALSE, @"Wrong notification delivered... not a valid UIDeviceOrientation notification");
			break;
	}
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
	sio2->_SIO2window->accel->x = acceleration.x * ( 1.0f - sio2->_SIO2window->accel_smooth ) + sio2->_SIO2window->accel->x * sio2->_SIO2window->accel_smooth;
	sio2->_SIO2window->accel->y = acceleration.y * ( 1.0f - sio2->_SIO2window->accel_smooth ) + sio2->_SIO2window->accel->y * sio2->_SIO2window->accel_smooth;
	sio2->_SIO2window->accel->z = acceleration.z * ( 1.0f - sio2->_SIO2window->accel_smooth ) + sio2->_SIO2window->accel->z * sio2->_SIO2window->accel_smooth;	

	sio2->_SIO2window->accel->x = ( int )( sio2->_SIO2window->accel->x * 100.0f );
	sio2->_SIO2window->accel->x *= 0.01f;

	sio2->_SIO2window->accel->y = ( int )( sio2->_SIO2window->accel->y * 100.0f );
	sio2->_SIO2window->accel->y *= 0.01f;		

	sio2ResourceDispatchEvents( sio2->_SIO2resource,
								sio2->_SIO2window,
								SIO2_WINDOW_ACCELEROMETER,
								SIO2_WINDOW_TAP_NONE );
}


-(void) connectionTest {
	
	static BOOL run = NO; 
	
	if (run == YES) {
		return;
	}
	else run = YES;
	
	Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
	NetworkStatus internetStatus = [r currentReachabilityStatus];
	BOOL connectionRequired= [r connectionRequired];
	
	if ((internetStatus == NotReachable))
	{
		UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"You require an internet connection via WiFi or cellular network for this app to work." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
		[myAlert show];
		[myAlert release];
		run = NO;
		return;
	} 
	
	else if ((internetStatus == ReachableViaWWAN) ||  (internetStatus == ReachableViaWiFi)) {
		
		if (connectionRequired) {
			NSURLConnection *conn = [[[NSURLConnection alloc] initWithRequest: 
									  [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.google.com"]
													   cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
												   timeoutInterval:2.0] delegate:self] autorelease]; 
			[conn start];
			[conn cancel];
		}
	}
	
	[self connectedToNetwork];
	
	MARK;
}

- (void) connectedToNetwork {
	
	NSURLConnection *theConnection = [[[NSURLConnection alloc] initWithRequest: 
									   [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.google.com"]
														cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 
													timeoutInterval:5.0] delegate:self] autorelease]; 
	
	if (!theConnection) {
		// inform the user that the download could not be made
		// if the connection fails, there is a delegate that is ready to handle it
		online = NO;
	}
	
	[theConnection start];
	
	MARK;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	
	UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Connection Test Failed" message:@"You require an internet connection via WiFi or cellular network for this app to work." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
	[myAlert show];
	[myAlert release];
	
	online = NO;
	MARK;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	online = YES;
	MARK;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	online = YES;
	MARK;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	online = YES;
	MARK;
}

- (void)dealloc {
	[[CCDirector sharedDirector] release];
	[window release];
	[glView release];
	[super dealloc];
}

@end
